<template>
  <div>
    <el-space direction="vertical" alignment="left" style="width: 100%">
      <el-card>
        <el-form ref="searchFormComponents" :model="searchForm" inline>
          <el-form-item label="老人姓名" prop="elderName">
            <el-input v-model="searchForm.elderName" placeholder="请输入姓名" clearable></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        <el-space>
          <!--          <el-button type="primary" @click="add" :icon="Plus">新增</el-button>-->
          <el-button type="danger" :icon="Delete" @click="batchDelete(null)" :disabled="selectionRows.length<=0">
            批量删除
          </el-button>
        </el-space>
      </el-card>
      <el-card>
        <el-table ref="tableComponents"
                  :data="listData"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @selection-change="selectionChange"
                  border>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" width="50"></el-table-column>
          <el-table-column prop="elderName" label="老人"></el-table-column>
          <el-table-column prop="reason" label="退住原因"></el-table-column>
          <el-table-column prop="expectedDate" label="计划退住日期"></el-table-column>
          <el-table-column prop="status" label="审批状态" width="100">
            <template #default="scope">
              <el-tag
                  :type="{
        0: 'info',
        1: 'success',
        2: 'danger'
      }[scope.row.status]"
                  effect="light"
              >
                {{
                  {
                    0: '未处理',
                    1: '审批通过',
                    2: '审批拒绝'
                  }[scope.row.status] || scope.row.status
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="processedByName" label="处理人"></el-table-column>
          <el-table-column prop="processTime" label="处理时间"></el-table-column>
          <el-table-column prop="notes" label="处理意见"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column prop="updateTime" label="修改时间"></el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button
                  type="success"
                  :icon="DocumentChecked"
                  @click="showApproveDialog(scope.row)"
                  :disabled="scope.row.status !== '0'"
              >审批
              </el-button>
              <el-button :icon="Delete" type="danger" @click="deleteOne(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-pagination
              @current-change="currentChange"
              @size-change="sizeChange"
              :page-size="pageInfo.pageSize"
              :current-page="pageInfo.currentPage"
              background
              layout="total,sizes, prev, pager, next"
              :total="pageInfo.total">
          </el-pagination>
        </div>
      </el-card>
    </el-space>
    <el-dialog
        v-model="approveDialogVisible"
        title="退住申请审批"
        width="500"
    >
      <el-form :model="approveForm" label-width="100px">
        <el-form-item label="审批结果" required>
          <el-radio-group v-model="approveForm.status">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
            label="审批意见"
            prop="notes"
            :rules="[{ required: true, message: '请输入审批意见' }]"
        >
          <el-input
              v-model="approveForm.notes"
              type="textarea"
              :rows="3"
              placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApproval">提交审批</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/http.js";
import {Check, Close, Delete, Edit, Refresh, Plus, Search, DocumentChecked} from '@element-plus/icons-vue'
import {ref, toRaw, reactive} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import dayjs from 'dayjs'
import utils from '@/utils/tools.js'

const searchFormComponents = ref();
const tableComponents = ref();
const listData = ref([]);
const pageInfo = ref({
  //当前页
  pageNum: 1,
  //分页大小
  pageSize: 10,
  //总条数
  total: 0
});
const searchForm = ref({});


getPageList()

/**
 * 获取分页数据
 */
function getPageList() {
  let data = Object.assign(toRaw(searchForm.value), toRaw(pageInfo.value))
  request.get("/checkoutApplication/page", {
    params: data
  }).then(res => {
    listData.value = res.data.list
    pageInfo.value.total = res.data.total
  })
}

/**
 * 选择分页
 * @param e
 */
function currentChange(e) {
  pageInfo.value.pageNum = e
  getPageList()
}

/**
 * 改变分页数量
 * @param e
 */
function sizeChange(e) {
  pageInfo.value.pageSize = e
  getPageList()
  console.log(e)
}

/**
 * 搜索
 */
function search() {
  pageInfo.value.pageNum = 1
  getPageList()
}

/**
 * 重置搜索框
 */
function resetSearch() {
  searchFormComponents.value.resetFields();
  getPageList()
}

const approveDialogVisible = ref(false)
const approveForm = reactive({
  id: null,
  status: '',
  notes: '',
  processedBy: '',
  processTime: '',
  elderId: '',
})

/**
 * 新增审批
 * @param row
 */
async function showApproveDialog(row) {
  approveForm.id = row.id
  approveForm.status = ''
  approveForm.notes = ''
  approveForm.processedBy = utils.getCurrentUser()?.id || ''
  approveForm.processTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  approveDialogVisible.value = true
  approveForm.elderId = row.elderId
}

/**
 * 提交审批
 */
async function submitApproval() {
  if (!approveForm.notes) {
    ElMessage.warning('请填写审批意见')
    return
  }

  try {
    await request.post('/checkoutApplication/approve', approveForm)
    ElMessage.success('审批提交成功')
    approveDialogVisible.value = false
    getPageList()
  } catch (error) {
    console.error('审批提交失败:', error)
    ElMessage.error('审批提交失败')
  }
}

const selectionRows = ref([]);

/**
 * 多选
 * @param rows
 */
function selectionChange(rows) {
  selectionRows.value = rows
}

/**
 * 单个删除
 * @param index
 * @param row
 */
function deleteOne(index, row) {
  batchDelete([row])
}

/**
 * 批量删除
 * @param rows
 */
function batchDelete(rows) {
  if (!rows) {
    rows = selectionRows.value;
  }
  let ids = rows.map(item => item.id);
  ElMessageBox.confirm(`此操作将永久删除ID为[${ids}]的数据, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(() => {
    request.delete("/checkoutApplication/delBatch", {data: ids}).then(res => {
      if (!res) {
        return
      }
      ElMessage({
        message: "操作成功",
        type: 'success'
      });
      getPageList()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
    tableComponents.value.clearSelection();
  });
}
</script>

<style scoped>

</style>
